<?php

namespace App\Http\Services;

use OSS\OssClient;
use OSS\Core\OssException;
use Illuminate\Support\Facades\Log;

class OssService
{
    public $sBucket = '';
    public $sACL    = '';

    public function __construct()
    {
        $this->sBucket = env('OSS_BUCKET');
        $this->sACL    = env('OSS_ACL');
    }

    /**
     * filePath  本地的文件绝对地址
     * targetPath  oss上要保存的地址路径，例如   voice/ceshi/houlai.mp3   voice为bucket名称，测试为bucket下的目录，houlai.mp3为要保存的文件名.
     */
    public function uploadFile($filePath, $targetPath)
    {
        try {
            $ossClient = app('oss');
            $result    = $ossClient->uploadFile($this->sBucket, $targetPath, $filePath);
            $httpCode  = $result['info']['http_code'] ?? 0;
            if (200 == $httpCode) {
//                $ossClient->putObjectAcl($this->sBucket, $targetPath, $this->sACL); //这里是我这边要设置文件权限为公共读，不设置会默认继承当前bucket上的权限，其他权限请参阅阿里云的oss官方文档
                return true;
            }

            return false;
        } catch (OssException $e) {
            Log::info('OSS-uploadFile_error', [$e->getMessage()]);

            return false;
        }
    }

    /**
     * targetPath  oss上文件的地址
     */
    public function existsFile($targetPath)
    {
        try {
            $ossClient = app('oss');

            return $ossClient->doesObjectExist($this->sBucket, $targetPath);
        } catch (OssException $e) {
            Log::channel('oss')->info('OSS-existsFile', [$e->getMessage()]);

            return false;
        }
    }

    /**
     * targetPath  oss上文件的地址
     * localPath   要保存到本地的绝对路径.
     */
    public function downFile($targetPath, $localPath)
    {
        try {
            $options                               = [];
            $options[OssClient::OSS_FILE_DOWNLOAD] = $localPath;
            $ossClient                             = app('oss');

            return $ossClient->doesObjectExist($this->sBucket, $targetPath, $options);
        } catch (OssException $e) {
            Log::channel('oss')->info('OSS-downFile', [$e->getMessage()]);

            return false;
        }
    }
}
